package com.ra.service.impl;

import com.ra.exception.BizException;
import com.ra.pojo.RespBean;
import com.ra.pojo.UserAuth;
import com.ra.mapper.UserAuthMapper;
import com.ra.pojo.dto.PasswordDTO;
import com.ra.pojo.dto.UserDetailsDTO;
import com.ra.service.IUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ra.service.JwtTokenService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import static com.ra.constant.AuthConstant.TOKEN_HEAD;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 今晚几点睡_Ada
 * @since 2023-03-09
 */
@Service
public class UserAuthServiceImpl extends ServiceImpl<UserAuthMapper, UserAuth> implements IUserAuthService {

    @Autowired
    private UserAuthMapper userAuthMapper;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenService jwtTokenService;

    @Override
    public RespBean<?> login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null||
                !passwordEncoder.matches(password,userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确!");
        }
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(userDetails, null,
                        userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", jwtTokenService.generateToken(userDetails));
        tokenMap.put("tokenHead", TOKEN_HEAD);
        return RespBean.success(tokenMap);
    }

    @Override
    public UserDetailsDTO getUserByUserName(String username) {
        return userAuthMapper.getUserByUserName(username);
    }


    @SneakyThrows
    @Override
    public RespBean<?> updateAdminPassword(PasswordDTO passwordDTO) {
        UserDetailsDTO userDetailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserAuth user = userAuthMapper.selectById(userDetailsDTO.getUserInfoId());
 /*       BCryptPasswordEncoder passwordEncoder =
                new BCryptPasswordEncoder();
        String hashpw = BCrypt.hashpw(passwordDTO.getNewPassword(), BCrypt.gensalt());
        String encode = passwordEncoder.encode(passwordDTO.getNewPassword());
        System.out.println("hashpw = " + hashpw);
        System.out.println("encode = " + encode);*/
      //判断输入的旧密码是否正确
        if(passwordEncoder.matches(passwordDTO.getOldPassword(),user.getPassword())){
            user.setPassword(BCrypt.hashpw(passwordDTO.getNewPassword(), BCrypt.gensalt()));
            if(userAuthMapper.updateById(user)==1){
                return RespBean.success("修改密码成功!");
            }
        }else {
            throw new BizException("旧密码不正确");
        }
        return RespBean.error("修改密码失败!");
    }


}
